package com.damai.action.json;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.db.Db;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.SignError;
import com.damai.action.json.impl.SignUtil;
import com.damai.error.NoMchError;
import com.damai.error.OuterError;
import com.damai.utils.LogUtil;

public class MchJsonParamParserFactory extends SimpleJsonParamParserFactory {
	
	
	private static MchJsonParamParserFactory DEFAULT = new MchJsonParamParserFactory();
	
	
	private static Map<String, String> map = new ConcurrentHashMap<String, String>();
	static{
		map.put("mch20170001", "f403814189edab87fc569545a8984739");
		map.put("mch20170002", "bfd013f77f3efc9b375aa63ddb3d08e1");
		map.put("mch20170003", "bfd013f77f3efc9b375aa63ddb3d08e1");
		map.put("mch20170921", "b696c85e27151470ba3b620cbd70c887");
	}
	
	public static MchJsonParamParserFactory getDef(){
		return DEFAULT;
	}
	
	
	public void add(String id,String key){
		map.put(id,key);
	}
	
	@Override
	public Map<String, Object> getJson(HttpServletRequest request) throws IOException {
		Map<String, Object> data = null;
		try{
			data = JsonUtil.read(request.getReader());
		}catch(IOException e){
			throw new OuterError(JsonUtil.ErrCode_Param, "ErrCode_Param");
		}
		
		String mchId = (String) data.get("mch_id");
		String key = map.get(mchId);
		//没有这个商户号
		if(key == null){
			key = Db.ar().where("CFG_KEY",mchId).getValue("sys_config", "CFG_VALUE");
			if(key == null) {
				throw new NoMchError(mchId);
			}else {
				map.put(mchId,key);
			}
		}
		//签名错误
		if(!SignUtil.validate(data,key)){
			LogUtil.log("%s %s",request.getServletPath(),data.toString());
			throw new SignError();
		}
		
		request.setAttribute("_mchId", mchId);
		request.setAttribute("_mchKey", key);
		
		return data;
	}
}
